import { Button, Cascader, InputNumber, Card, Form, Input, Radio, Divider, App, Popconfirm } from 'antd'
import { PageContainer } from '@ant-design/pro-components'
import CITY from '@/utils/city.json'
import FormUploadImg from '@/components/FormUploadImg'
import styles from './MerchantDetail.less'
import { useEffect, useState } from 'react'
import { useModel, useSearchParams } from '@umijs/max'
import { Space } from 'antd'

const MerchantDetails = () => {
  const { MerchantInfo, AddSettle, UpdateMerchant } = useModel('Merchant')
  const { message } = App.useApp()

  const [addAndEditFormRef] = Form.useForm()
  const [searchParams] = useSearchParams()

  const [currentId, setCurrentId] = useState(null) // 当前 id
  const [currentType, setCurrentType] = useState(null) // 当前 type
  const [initialValues, setInitialValues] = useState({
    settle_type: 2,
    status: 1,
    withdrawal_rate: 0,
    gain_tx_rate: 0
  })

  useEffect(() => {
    let id = searchParams.get('id')
    let type = searchParams.get('type')

    setCurrentId(id)
    setCurrentType(type)

    if (type === 'edit') {
      getDetailsInfo(id)
    }
  }, [])

  // 获取详情
  const getDetailsInfo = async id => {
    const res = await MerchantInfo({ id })
    if (res) {
      let data = res
      const formData = {
        ...data,
        company_address: [data.company_province, data.company_city, data.company_area]
        // sign_address: [data.province, data.city, data.area]
      }
      setInitialValues(formData)
      addAndEditFormRef.setFieldsValue(formData)
    }
  }

  const handleSubmit = async values => {
    let params = {
      ...values,

      // 公司地址
      company_province: values.company_address[0],
      company_city: values.company_address[1],
      company_area: values.company_address[2]

      // 合同签署地址
      // province: values.sign_address[0],
      // city: values.sign_address[1],
      // area: values.sign_address[2],
      // sign_address: values.sign_address.join('')
    }

    delete params.company_address

    let res = null
    if (currentType === 'add') {
      res = await AddSettle(params)
    } else if (currentType === 'edit') {
      res = await UpdateMerchant({ ...params, id: currentId })
    }

    if (res) {
      message.success('操作成功')
    }
  }

  // 更改合同约定诉讼法院
  // const handleChangeSignAddress = value => {
  //   addAndEditFormRef.setFieldsValue({
  //     court_name: value.join('') + '人民法院'
  //   })
  // }

  const formatExtra = () => {
    return [
      <Popconfirm
        key='cancel'
        title='你确认取消吗？'
        onConfirm={() => addAndEditFormRef.resetFields()}
        okText='确认'
        cancelText='取消'
      >
        <Button>取消</Button>
      </Popconfirm>,
      <Popconfirm
        key='submit'
        title='你确认保存吗？'
        onConfirm={() => addAndEditFormRef.submit()}
        okText='确认'
        cancelText='取消'
      >
        <Button type='primary'>保存</Button>
      </Popconfirm>
    ]
  }

  const RateItem = ({ onChange, value }) => {
    useEffect(() => {
      console.log('value', value)
    }, [value])
    const handleChange = e => {
      console.log('onChange', e.target.value)
      onChange(e.target.value)
    }
    return (
      <Radio.Group onChange={handleChange} value={value}>
        <Space direction='vertical' size='middle'>
          <Radio value={0}>租金结算（每期到账金额的百分比结算给平台）</Radio>
          {value === 0 ? (
            <div className={styles.rate_content}>
              <Form.Item
                name='withdrawal_rate'
                label='手续费'
                labelCol={{ span: 5 }}
                rules={[{ required: true, message: '请输入手续费' }]}
              >
                <InputNumber controls={false} precision={0} addonBefore='结算手续费' max={100} min={0} addonAfter='%' />
              </Form.Item>

              <Form.Item
                name='gain_tx_rate'
                label='增值服务'
                labelCol={{ span: 5 }}
                rules={[{ required: true, message: '请输入增值服务提现费率' }]}
              >
                <InputNumber controls={false} precision={0} addonBefore='结算手续费' max={100} min={0} addonAfter='%' />
              </Form.Item>
            </div>
          ) : null}
          <Radio value={1}>成交结算（订单成交额的百分比结算给平台_____只结算一次不包含增值服务）</Radio>
          {value === 1 ? (
            <div className={styles.rate_content}>
              <Form.Item
                name='transaction_rate'
                label='手续费'
                labelCol={{ span: 5 }}
                rules={[{ required: true, message: '请输入手续费' }]}
              >
                <InputNumber controls={false} precision={0} addonBefore='结算手续费' max={100} min={0} addonAfter='%' />
              </Form.Item>
            </div>
          ) : null}
        </Space>
      </Radio.Group>
    )
  }

  return (
    <div className={styles.merchant_details}>
      <PageContainer
        header={{
          fixedHeader: true,
          title: (
            <div className={styles.header_title}>
              <span>{currentType === 'add' ? '添加商户' : '编辑商户'}</span>
              <Divider type='vertical' />
              <span className={styles.header_desc}>{currentType === 'add' ? '新增' : '编辑'}商户信息配置页</span>
            </div>
          ),
          extra: formatExtra()
        }}
      >
        <Form
          preserve={false}
          form={addAndEditFormRef}
          name='addAndEdit'
          initialValues={initialValues}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 10 }}
          onFinish={values => handleSubmit(values)}
        >
          <Card title='基础信息' bordered={false} style={{ marginBottom: 20 }}>
            <Form.Item name='corporate_name' label='公司全称: ' rules={[{ required: true, message: '请输入企业名称' }]}>
              <Input placeholder='请输入企业名称' allowClear />
            </Form.Item>

            <FormUploadImg
              extra='用户展示在小程序前台的店铺头像，请选择3MB以内的正方形图片上传'
              required
              name='shop_head_portrait'
              label='店招图片'
            />

            <Form.Item name='shop_name' label='店铺名称: ' rules={[{ required: true, message: '请输入店铺名称' }]}>
              <Input placeholder='请输入店铺名称' allowClear />
            </Form.Item>

            <Form.Item
              name='contact_tel'
              label='联系电话: '
              rules={[
                { required: true, message: '请输入联系电话' },
                { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确' }
              ]}
            >
              <Input placeholder='请输入联系电话' allowClear />
            </Form.Item>

            <Form.Item name='settle_type' label='商户类型: ' rules={[{ required: true, message: '请选择商户类型' }]}>
              <Radio.Group>
                <Radio value={1}>自营</Radio>
                <Radio value={2}>加盟</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item name='reg_no' label='营业执照号: ' rules={[{ required: true, message: '请输入营业执照号' }]}>
              <Input placeholder='请输入营业执照号' allowClear />
            </Form.Item>

            <Form.Item
              name='company_address'
              label='营业执照地址: '
              rules={[{ required: true, message: '请选择营业执照地址' }]}
            >
              <Cascader options={CITY} placeholder='营业执照地址' />
            </Form.Item>

            <Form.Item
              name='company_detail_address'
              label='详细地址: '
              rules={[{ required: true, message: '请选择详细地址' }]}
            >
              <Input placeholder='请选择详细地址' allowClear />
            </Form.Item>

            <FormUploadImg required name='license_pic' label='营业执照' />

            <Form.Item name='status' label='启用状态: ' rules={[{ required: true, message: '请选择启用状态' }]}>
              <Radio.Group>
                <Radio value={1}>启用</Radio>
                <Radio value={2}>停用</Radio>
              </Radio.Group>
            </Form.Item>
          </Card>

          <Card title='法人信息' style={{ marginBottom: 20 }}>
            <Form.Item
              name='legal_person_name'
              label='法人姓名: '
              rules={[{ required: true, message: '请输入法人姓名' }]}
            >
              <Input placeholder='请输入法人姓名' allowClear />
            </Form.Item>

            <Form.Item
              name='legal_person_id_num'
              label='法人身份证号: '
              rules={[{ required: true, message: '请输入法人身份证号' }]}
            >
              <Input placeholder='请输入法人身份证号' allowClear />
            </Form.Item>

            <FormUploadImg required name='legal_person_front_card_pic' label='法人身份证正面' />

            <FormUploadImg required name='legal_person_back_card_pic' label='法人身份证背面' />
          </Card>

          <Card title='费率设置' style={{ marginBottom: 20 }}>
            {/* <Form.Item
              name='withdrawal_rate'
              label='店铺提现手续费'
              rules={[{ required: true, message: '请输入店铺提现手续费' }]}
            >
              <InputNumber controls={false} precision={0} addonBefore='手续费率' max={100} min={0} addonAfter='%' />
            </Form.Item>

            <Form.Item
              name='gain_tx_rate'
              label='增值服务提现费率'
              rules={[{ required: true, message: '请输入增值服务提现费率' }]}
            >
              <InputNumber controls={false} precision={0} addonBefore='手续费率' max={100} min={0} addonAfter='%' />
            </Form.Item> */}

            <Form.Item name='settlement_type' label='结算规则' rules={[{ required: true, message: '请选择结算规则' }]}>
              <RateItem></RateItem>
            </Form.Item>
          </Card>

          <Card title='风控收费设置' style={{ marginBottom: 20 }}>
            <Form.Item
              name='boole'
              label='金盾风控'
              labelCol={{ span: 5 }}
              rules={[{ required: true, message: '金盾风控' }]}
            >
              <InputNumber controls={false} precision={2} addonBefore='金盾风控' min={0} />
            </Form.Item>
            <Form.Item
              name='risk'
              label='风控报告'
              labelCol={{ span: 5 }}
              rules={[{ required: true, message: '风控报告' }]}
            >
              <InputNumber controls={false} precision={2} min={0} />
            </Form.Item>
            <Form.Item
              name='cyc_data'
              label='消费能力报告'
              labelCol={{ span: 5 }}
              rules={[{ required: true, message: '消费能力报告' }]}
            >
              <InputNumber controls={false} precision={2} min={0} />
            </Form.Item>
            <Form.Item
              name='credit'
              label='征信报告'
              labelCol={{ span: 5 }}
              rules={[{ required: true, message: '征信报告' }]}
            >
              <InputNumber controls={false} precision={2} min={0} />
            </Form.Item>
            <Form.Item
              name='youfen'
              label='优分风控'
              labelCol={{ span: 5 }}
              rules={[{ required: true, message: '优分风控' }]}
            >
              <InputNumber controls={false} precision={2} min={0} />
            </Form.Item>
            <Form.Item
              name='liehuzuo_risk'
              label='微盾风控'
              labelCol={{ span: 5 }}
              rules={[{ required: true, message: '微盾风控' }]}
            >
              <InputNumber controls={false} precision={2} min={0} />
            </Form.Item>
            <Form.Item
              name='boole_zzb'
              label='金盾-至臻版'
              labelCol={{ span: 5 }}
              rules={[{ required: true, message: '金盾-至臻版' }]}
            >
              <InputNumber controls={false} precision={2} min={0} />
            </Form.Item>
          </Card>

          <Card title='蚂蚁链支付配置' style={{ marginBottom: 20 }}>
            <Form.Item
              name='esign_seal_id'
              extra={
                <div>
                  E签宝ID如何获取 :
                  <a
                    href='https://www.yuque.com/u33626086/bqgsnf/vuufibb99rrhyvfs?singleDoc# 《E签宝商家印章创建授权流程》'
                    target='_blank'
                    rel='noreferrer'
                  >
                    https://www.yuque.com/u33626086/bqgsnf/vuufibb99rrhyvfs?singleDoc# 《E签宝商家印章创建授权流程》
                  </a>
                </div>
              }
              label='E签宝ID'
            >
              <Input placeholder='请输入E签宝ID' allowClear />
            </Form.Item>
          </Card>

          {/* <Form.Item wrapperCol={{ offset: 2 }}>
            <Popconfirm
              title='你确认提交吗？'
              onConfirm={() => addAndEditFormRef.submit()}
              okText='确认'
              cancelText='取消'
            >
              <Button type='primary'>提交</Button>
            </Popconfirm>
          </Form.Item> */}
        </Form>
      </PageContainer>
    </div>
  )
}

export default MerchantDetails
